<template>
  <el-drawer
    v-model="visible"
    :title="`供应商 ${supplierName} 的交易记录`"
    size="60%"
    direction="rtl"
    :before-close="handleClose"
  >
    <div class="transaction-records-container">
      <el-tabs v-model="activeTab" class="transaction-tabs">
        <!-- 银行流水记录 -->
        <el-tab-pane label="银行流水记录" name="bankTransactions">
          <div class="tab-content">
            <div class="tab-header">
              <el-text class="mx-1">最近半年的银行流水记录</el-text>
              <el-button 
                type="primary" 
                :icon="Refresh" 
                @click="loadBankTransactions"
                :loading="loading.bankTransactions"
                size="small"
              >
                刷新
              </el-button>
            </div>
            
            <el-table
              :data="bankTransactions"
              v-loading="loading.bankTransactions"
              stripe
              style="width: 100%"
              max-height="400"
            >
              <el-table-column prop="transactionId" label="流水号" width="180" />
              <el-table-column prop="payerName" label="付款方" width="150" />
              <el-table-column prop="amount" label="金额" width="120">
                <template #default="{ row }">
                  ¥{{ row.amount.toLocaleString() }}
                </template>
              </el-table-column>
              <el-table-column prop="transactionDate" label="交易日期" width="120">
                <template #default="{ row }">
                  {{ formatDate(row.transactionDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="transactionTime" label="交易时间" width="120" />
              <el-table-column prop="remark" label="备注" show-overflow-tooltip />
            </el-table>
            
            <div class="pagination-container" v-if="bankTransactions.length > 0">
              <el-pagination
                v-model:current-page="bankTransactionPagination.currentPage"
                v-model:page-size="bankTransactionPagination.pageSize"
                :page-sizes="[10, 20, 50]"
                :total="bankTransactionPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleBankTransactionSizeChange"
                @current-change="handleBankTransactionCurrentChange"
              />
            </div>
            
            <el-empty 
              v-if="bankTransactions.length === 0 && !loading.bankTransactions" 
              description="暂无银行流水记录" 
            />
          </div>
        </el-tab-pane>
        
        <!-- 采购记录 -->
        <el-tab-pane label="采购记录" name="purchaseRecords">
          <div class="tab-content">
            <div class="tab-header">
              <el-text class="mx-1">最近一年的采购记录</el-text>
              <el-button 
                type="primary" 
                :icon="Refresh" 
                @click="loadPurchaseRecords"
                :loading="loading.purchaseRecords"
                size="small"
              >
                刷新
              </el-button>
            </div>
            
            <el-table
              :data="purchaseRecords"
              v-loading="loading.purchaseRecords"
              stripe
              style="width: 100%"
              max-height="400"
            >
              <el-table-column prop="orderNumber" label="采购单号" width="150" />
              <el-table-column prop="supplierName" label="供应商" width="150" />
              <el-table-column prop="totalAmount" label="总金额" width="120">
                <template #default="{ row }">
                  ¥{{ row.totalAmount.toLocaleString() }}
                </template>
              </el-table-column>
              <el-table-column prop="orderDate" label="下单日期" width="120">
                <template #default="{ row }">
                  {{ formatDate(row.orderDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getPurchaseOrderStatusType(row.status)">
                    {{ getPurchaseOrderStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" show-overflow-tooltip />
            </el-table>
            
            <div class="pagination-container" v-if="purchaseRecords.length > 0">
              <el-pagination
                v-model:current-page="purchaseRecordPagination.currentPage"
                v-model:page-size="purchaseRecordPagination.pageSize"
                :page-sizes="[10, 20, 50]"
                :total="purchaseRecordPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handlePurchaseRecordSizeChange"
                @current-change="handlePurchaseRecordCurrentChange"
              />
            </div>
            
            <el-empty 
              v-if="purchaseRecords.length === 0 && !loading.purchaseRecords" 
              description="暂无采购记录" 
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as procurementAPI from '@/api/procurement'
import * as reconciliationAPI from '@/api/reconciliation'

// 定义属性
const props = defineProps<{
  modelValue: boolean
  supplierId: number
  supplierName: string
}>()

// 定义事件
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'close'): void
}>()

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

const activeTab = ref('bankTransactions')

// 银行流水记录相关
const bankTransactions = ref<any[]>([])
const bankTransactionPagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 采购记录相关
const purchaseRecords = ref<any[]>([])
const purchaseRecordPagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 加载状态
const loading = ref({
  bankTransactions: false,
  purchaseRecords: false
})

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    if (isNaN(date.getTime())) return dateString
    return date.toLocaleDateString('zh-CN')
  } catch (error) {
    return dateString
  }
}

// 获取采购订单状态类型
const getPurchaseOrderStatusType = (status: string) => {
  switch (status) {
    case 'pending': return 'warning'
    case 'confirmed': return 'primary'
    case 'completed': return 'success'
    case 'cancelled': return 'danger'
    default: return 'info'
  }
}

// 获取采购订单状态文本
const getPurchaseOrderStatusText = (status: string) => {
  switch (status) {
    case 'pending': return '待确认'
    case 'confirmed': return '已确认'
    case 'completed': return '已完成'
    case 'cancelled': return '已取消'
    default: return '未知状态'
  }
}

// 加载银行流水记录
const loadBankTransactions = async () => {
  console.log('加载银行流水记录，当前页:', bankTransactionPagination.value.currentPage, '页面大小:', bankTransactionPagination.value.pageSize);
  loading.value.bankTransactions = true
  try {
    // 这里需要根据供应商信息查询相关的银行流水记录
    // 目前我们先加载所有银行流水，后续可以根据供应商名称进行筛选
    const response = await reconciliationAPI.getBankTransactions({
      page: bankTransactionPagination.value.currentPage,
      limit: bankTransactionPagination.value.pageSize,
      supplierId: props.supplierId // 根据供应商ID筛选
    })
    
    bankTransactions.value = response.data?.list || []
    bankTransactionPagination.value.total = response.data?.pagination?.total || 0
  } catch (error) {
    ElMessage.error('加载银行流水记录失败: ' + (error as Error).message)
  } finally {
    loading.value.bankTransactions = false
  }
}

// 加载采购记录
const loadPurchaseRecords = async () => {
  console.log('加载采购记录，当前页:', purchaseRecordPagination.value.currentPage, '页面大小:', purchaseRecordPagination.value.pageSize);
  loading.value.purchaseRecords = true
  try {
    // 这里需要根据供应商ID查询相关的采购记录
    // 由于目前没有采购记录API，我们先使用模拟数据
    const response = await procurementAPI.getInboundOrders({
      page: purchaseRecordPagination.value.currentPage,
      limit: purchaseRecordPagination.value.pageSize,
      supplierId: props.supplierId
    })
    
    purchaseRecords.value = response.data.list || []
    purchaseRecordPagination.value.total = response.data?.pagination?.total || 0
  } catch (error) {
    ElMessage.error('加载采购记录失败: ' + (error as Error).message)
  } finally {
    loading.value.purchaseRecords = false
  }
}

// 处理银行流水分页大小变化
const handleBankTransactionSizeChange = (size: number) => {
  console.log('银行流水分页大小变化:', size);
  bankTransactionPagination.value.pageSize = size
  loadBankTransactions()
}

// 处理银行流水分页页码变化
const handleBankTransactionCurrentChange = (page: number) => {
  console.log('银行流水分页页码变化:', page);
  bankTransactionPagination.value.currentPage = page
  loadBankTransactions()
}

// 处理采购记录分页大小变化
const handlePurchaseRecordSizeChange = (size: number) => {
  console.log('采购记录分页大小变化:', size);
  purchaseRecordPagination.value.pageSize = size
  loadPurchaseRecords()
}

// 处理采购记录分页页码变化
const handlePurchaseRecordCurrentChange = (page: number) => {
  console.log('采购记录分页页码变化:', page);
  purchaseRecordPagination.value.currentPage = page
  loadPurchaseRecords()
}

// 关闭抽屉
const handleClose = () => {
  visible.value = false
  emit('close')
}

// 监听抽屉显示状态变化
watch(() => visible.value, (newVal: boolean) => {
  if (newVal) {
    // 重置分页
    bankTransactionPagination.value.currentPage = 1
    purchaseRecordPagination.value.currentPage = 1
    
    // 只加载默认激活的标签页数据（银行流水记录）
    if (activeTab.value === 'bankTransactions') {
      loadBankTransactions()
    }
  }
})

// 监听标签页变化
watch(() => activeTab.value, (newVal: string, oldVal: string) => {
  // 只有当抽屉已显示时才加载数据
  if (visible.value && newVal !== oldVal) {
    if (newVal === 'bankTransactions') {
      // 如果银行流水记录还没有加载过，则加载数据
      if (bankTransactions.value.length === 0) {
        loadBankTransactions()
      }
    } else if (newVal === 'purchaseRecords') {
      // 如果采购记录还没有加载过，则加载数据
      if (purchaseRecords.value.length === 0) {
        loadPurchaseRecords()
      }
    }
  }
})

// 监听供应商ID变化，但只有在抽屉已经显示时才重新加载
watch(() => props.supplierId, (newVal: number, oldVal: number) => {
  // 只有当供应商ID真正改变且抽屉已显示时才重新加载
  if (newVal !== oldVal && visible.value) {
    // 重置分页
    bankTransactionPagination.value.currentPage = 1
    purchaseRecordPagination.value.currentPage = 1
    
    // 清空现有数据
    bankTransactions.value = []
    purchaseRecords.value = []
    
    // 根据当前激活的标签页加载相应数据
    if (activeTab.value === 'bankTransactions') {
      loadBankTransactions()
    } else if (activeTab.value === 'purchaseRecords') {
      loadPurchaseRecords()
    }
  }
})
</script>

<style scoped>
.transaction-records-container {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.transaction-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.transaction-tabs :deep(.el-tabs__content) {
  flex: 1;
  overflow: hidden;
}

.tab-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  flex: 1;
}
</style>